# coding=utf8
import click
import time
import saltedpwd

from hashlib import sha256
from app import create_app

@click.group()
def cli():
    pass

@click.command()
@click.option('--bind', default='127.0.0.1', help='host name for listen')
@click.option('--port', default=8000, help='port for listen')
def runserver(bind, port):
    app = create_app()
    app.run(host=bind, port=port, debug=True)


@click.command()
def try_token():
    from www.weixinService import AccessTokenService
    accessTokenService = AccessTokenService.try_grant()
    if accessTokenService.error_msg:
        click.echo("ERROR:%s" % accessTokenService.error_msg)
    else:
        click.echo("Token:%s" % accessTokenService.token )
        rs, info = accessTokenService.getTicket()
        click.echo("RS:%s %s" % (rs, info))
        click.echo(accessTokenService.sign(int(time.time()), "http://running.17gaoshiqing/regist"))



@click.command()
@click.argument('email')
@click.argument('password')
def new_mng(email, password):
    from database import db
    from models import Manager
    if Manager.query.filter(Manager.email == email).first():
        return click.echo('该邮箱已经被占用了')
    salted = saltedpwd.Salted(sha256)
    db.add(Manager(email=email, password=salted.gen_password(password), valid=1))
    db.commit()
    return click.echo("帐号已经创建")


@click.command()
def mngs():
    from models import Manager
    for manager in Manager.query.filter().all():
        click.echo("[%s]--> %s\t|\t%s" % (manager.id, manager.email, "T" if manager.valid else "F"))
        click.echo("------------------------")
        
@click.command()
@click.argument('mid')
def mng_switch(mid):
    from models import Manager
    from database import db
    manager = Manager.query.filter(Manager.id == int(mid)).first()
    if not manager:
        return click.echo('没有这个管理员')
    manager.valid = abs(1 - manager.valid)
    db.commit()
    click.echo('修改状态完成!')


@click.command()
@click.argument('mid')
@click.argument('password')
def mng_pwd(mid, password):
    from models import Manager
    from database import db
    manager = Manager.query.filter(Manager.id == int(mid)).first()
    if not manager:
        return click.echo('没有这个管理员')
    salted = saltedpwd.Salted(sha256)
    manager.password = salted.gen_password(password)
    db.commit()
    click.echo('重置密码完成!')




cli.add_command(runserver)
cli.add_command(try_token)
cli.add_command(new_mng)
cli.add_command(mngs)
cli.add_command(mng_switch)
cli.add_command(mng_pwd)
cli()